package mtn.bowen.yan.server.service.impl;

import com.jfoenix.controls.JFXRadioButton;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import mtn.bowen.yan.server.common.Constant;
import mtn.bowen.yan.server.dao.PictureOfDishesDao;
import mtn.bowen.yan.server.dao.VarietyDishesDao;
import mtn.bowen.yan.server.enums.DishesKindEnum;
import mtn.bowen.yan.server.enums.DishesTypeEnum;
import mtn.bowen.yan.server.enums.ErrorCode;
import mtn.bowen.yan.server.enums.WeekEnum;
import mtn.bowen.yan.server.exception.CaiPuServerException;
import mtn.bowen.yan.server.fx.StageManager;
import mtn.bowen.yan.server.model.PictureDishes;
import mtn.bowen.yan.server.model.VarietyDishes;
import mtn.bowen.yan.server.model.WeekRecipe;
import mtn.bowen.yan.server.service.JavaFxUiService;
import mtn.bowen.yan.server.service.PictureDishesService;
import mtn.bowen.yan.server.service.VarietyDishesService;
import mtn.bowen.yan.server.service.WeekRecipeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @author <a href=mailto:yanbowen90@foxmail.com> bowen.yan </a>
 * @version 1.0
 * @description: TODO
 * @date 2021-10-23 9:45 PM
 */
@Component
public class VarietyDishesServiceImpl implements VarietyDishesService {

    private final static Logger LOGGER = LoggerFactory.getLogger(VarietyDishesServiceImpl.class);

    @Resource
    private VarietyDishesDao varietyDishesDao;

    @Resource
    private JavaFxUiService javaFxUiService;

    @Resource
    private WeekRecipeService weekRecipeService;

    @Resource
    private PictureOfDishesDao pictureOfDishesDao;

    @Resource
    private PictureDishesService pictureDishesService;

    /**
     * 获取所有菜品类型
     *
     * @return 全部菜品类型
     */
    @Override
    public List<VarietyDishes> getAllDishes() {

        try {
            List<VarietyDishes> all = varietyDishesDao.selectAll();
            return all;
        } catch (Exception e) {
            LOGGER.error("VarietyDishesServiceImpl.getAllDishes is error", e);
            throw new CaiPuServerException(ErrorCode.SYSTEM_EXCEPTION, "查询失败！");
        }
    }

    /**
     * 按照类型获取菜品
     *
     * @param typeEnum 类型
     * @return 此类型的所有菜品
     */
    @Override
    public List<VarietyDishes> getDishesByType(DishesTypeEnum typeEnum) {
        List<VarietyDishes> result = null;

        try {
            result = varietyDishesDao.selectByType(typeEnum.getCode());
            return result;
        } catch (Exception e) {
            LOGGER.error("VarietyDishesServiceImpl.getDishesByType is error", e);
            throw new CaiPuServerException(ErrorCode.SYSTEM_EXCEPTION, "查询失败！");
        }
    }

    /**
     * 按照类型与星期获取菜品
     *
     * @param typeEnum 类型
     * @param weekEnum 星期
     * @return 此类型的所有菜品
     */
    @Override
    public List<VarietyDishes> getDishesByTypeAndWeek(DishesTypeEnum typeEnum, WeekEnum weekEnum) {
        List<VarietyDishes> result = null;

        try {
            result = varietyDishesDao.selectByTypeAndWeek(typeEnum.getCode(), weekEnum.getCode());
            return result;
        } catch (Exception e) {
            LOGGER.error("VarietyDishesServiceImpl.getDishesByTypeAndWeek is error", e);
            throw new CaiPuServerException(ErrorCode.SYSTEM_EXCEPTION, "查询失败！");
        }
    }

    /**
     * 按照类型与星期获取菜品
     *
     * @param typeEnum 类型
     * @param weekEnum 星期
     * @return 此类型的所有菜品
     */
    @Override
    public List<VarietyDishes> getDishesByTypeAndWeek(int typeEnum, int weekEnum) {
        List<VarietyDishes> result = null;

        try {
            result = varietyDishesDao.selectByTypeAndWeek(typeEnum, weekEnum);
            return result;
        } catch (Exception e) {
            LOGGER.error("VarietyDishesServiceImpl.getDishesByTypeAndWeek is error", e);
            throw new CaiPuServerException(ErrorCode.SYSTEM_EXCEPTION, "查询失败！");
        }
    }

    /**
     * 设置TabPane内容
     *
     * @param tabPane 上下文
     */
    @Override
    public void setTabPane(TabPane tabPane, DishesTypeEnum typeEnum, WeekEnum weekEnum) {

        List<VarietyDishes> list = getDishesByTypeAndWeek(typeEnum, weekEnum);
        // 排序
        Collections.sort(list);
        list.forEach(item -> {
            if (!item.getQuantity().equals(Constant.NUMBER_OF_DISHES_IS_ZERO)) {
                Tab tab = makeKindTab(item);
                tabPane.getTabs().add(tab);
            }
        });
    }

    /**
     * 存储食谱类型种类
     *
     * @param vDishes 菜品类型种类
     */
    @Override
    public Integer saveVarietyDishes(VarietyDishes vDishes) {

        return varietyDishesDao.insertOnUpdate(vDishes);
    }

    /**
     * 生成菜品种类图片
     *
     * @param varietyDishes 每种类型的种类数据
     * @return Tab
     */
    @Override
    public Tab makeKindTab(VarietyDishes varietyDishes) {
        int quantity = varietyDishes.getQuantity();
        DishesKindEnum kind = DishesKindEnum.getDishesKind(varietyDishes.getKind());
        Tab tab = new Tab();
        tab.setText(kind.getMsg());
        tab.setClosable(false);

        //上部分
        HBox up = javaFxUiService.getTabHBox(Pos.CENTER_LEFT);
        List<WeekRecipe> weekRecipes = weekRecipeService.selectByWeekAndTypeAndKind(varietyDishes);

        if (weekRecipes != null && weekRecipes.size() != 0) {

            weekRecipes.forEach(weekRecipe -> {
                VBox mBox = javaFxUiService.getVBox(new Insets(10, 10, 10, 10));
                ImageView view = javaFxUiService.getImageView(150.0, 150.0, "/picture/" + weekRecipe.getUuid());
                Text text = javaFxUiService.getText(weekRecipe.getName(), Font.font("KaiTi", FontWeight.NORMAL, 22));

                mBox.getChildren().add(view);
                mBox.getChildren().add(text);
                up.getChildren().add(mBox);
            });
        } else {
            for (int i = 0; i < quantity; i++) {
                VBox mBox = javaFxUiService.getVBox(new Insets(10, 10, 10, 10));
                ImageView view = javaFxUiService.getImageView(150.0, 150.0, "/icons/ToChooseOne.png");
                Text text = javaFxUiService.getText("待选菜品", Font.font("KaiTi", FontWeight.NORMAL, 22));

                mBox.getChildren().add(view);
                mBox.getChildren().add(text);
                up.getChildren().add(mBox);
            }
        }

        //下部分
        HBox downFull = javaFxUiService.getHBox(Pos.CENTER_LEFT, 10.0, new Insets(10, 10, 10, 10));
        List<PictureDishes> pictureDishesByKind = pictureOfDishesDao.selectByKind(varietyDishes.getKind());
        int allRow = pictureDishesService.getRow(pictureDishesByKind.size(), Constant.DELETE_RECIPE_COLUMN);
        int tempRow = allRow;
        VBox allVBox = new VBox();
        try {
            int count = 0;
            int flag = 0;
            for (int row = 0; row < allRow; row++) {
                HBox hBox = javaFxUiService.getPictureHBox(Pos.CENTER_LEFT, new Insets(10, 10, 10, 10));
                hBox.setSpacing(60);
                if (tempRow >= 2) {
                    for (int col = 0; col < Constant.DELETE_RECIPE_COLUMN; col++) {
                        PictureDishes pictureDishes = pictureDishesByKind.get(flag);
                        VBox vBox = javaFxUiService.getVBox(new Insets(10, 10, 10, 10));
                        ImageView view = javaFxUiService.getImageView(150.0, 150.0, "/picture/" + pictureDishes.getUuid());
                        JFXRadioButton jButton = new JFXRadioButton(pictureDishes.getName());
                        jButton.setStyle("-fx-font-family: STKaiTi;-fx-border-width: 1px;-fx-font-size: 22;");
                        vBox.getChildren().add(view);
                        vBox.getChildren().add(jButton);
                        //设置标志位 set in Map
                        jButton.setId(pictureDishes.getUuid() + "#" + pictureDishes.getName());
                        jButton.setOnAction(event -> {
                            String[] split = jButton.getId().split("#");
                            //存储数据
                            WeekRecipe build = WeekRecipe.builder().week(varietyDishes.getWeek()).type(varietyDishes.getType()).kind(varietyDishes.getKind()).uuid(split[0]).name(split[1]).build();
                            StageManager.addWeekRecipeMapDropIfExists(jButton.getId(), build);
                        });
                        hBox.getChildren().add(vBox);
                        count++;
                        flag++;
                    }
                    tempRow--;
                    allVBox.getChildren().add(hBox);
                } else {
                    for (int col = 0; col < pictureDishesByKind.size() - count; col++) {
                        PictureDishes pictureDishes = pictureDishesByKind.get(flag);
                        VBox vBox = javaFxUiService.getVBox(new Insets(10, 10, 10, 10));
                        ImageView view = javaFxUiService.getImageView(150.0, 150.0, "/picture/" + pictureDishes.getUuid());
                        JFXRadioButton jButton = new JFXRadioButton(pictureDishes.getName());
                        jButton.setStyle("-fx-font-family: STKaiTi;-fx-border-width: 1px;-fx-font-size: 22;");
                        vBox.getChildren().add(view);
                        vBox.getChildren().add(jButton);
                        //设置标志位 set in Map
                        jButton.setId(pictureDishes.getUuid() + "#" + pictureDishes.getName());
                        jButton.setOnAction(event -> {
                            String[] split = jButton.getId().split("#");
                            //存储数据
                            WeekRecipe build = WeekRecipe.builder().week(varietyDishes.getWeek()).type(varietyDishes.getType()).kind(varietyDishes.getKind()).uuid(split[0]).name(split[1]).build();
                            StageManager.addWeekRecipeMapDropIfExists(jButton.getId(), build);
                        });
                        hBox.getChildren().add(vBox);
                        flag++;
                    }
                    allVBox.getChildren().add(hBox);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

//        VBox down = new VBox();
//        down.setSpacing(25.0);
//        for (int row = 0; row < 3; row++) {
//            HBox downHBox = new HBox();
//            downHBox.setSpacing(30.0);
//            for (int col = 0; col < 8; col++) {
//                VBox downHBoxVBox = new VBox();
//                downHBoxVBox.setAlignment(Pos.CENTER);
//                ImageView view = javaFxUiService.getImageView(150.0, 150.0, "/icons/ToChooseOne.png");
//                Text text = javaFxUiService.getText("待选菜品", Font.font("KaiTi", FontWeight.NORMAL, 22));
//
//                downHBoxVBox.getChildren().add(view);
//                downHBoxVBox.getChildren().add(text);
//                downHBox.getChildren().add(downHBoxVBox);
//            }
//            down.getChildren().add(downHBox);
//        }

        downFull.getChildren().add(allVBox);

        //整个面板
        VBox fullPane = javaFxUiService.getVBox(new Insets(20, 5, 20, 5));
        fullPane.setSpacing(20.0);
        fullPane.getChildren().add(up);
        fullPane.getChildren().add(downFull);
        fullPane.setAlignment(Pos.TOP_LEFT);

        tab.setContent(fullPane);
        return tab;
    }
}
